//
//  MK_Barrage_FloatView.m
//  miku直播
//
//  Created by 杨尚达 on 2017/7/30.
//  Copyright © 2017年 杨尚达. All rights reserved.
//

#import "MK_Barrage_FloatView.h"
#import "MK_BarrageManager.h"
#define fontsize 16

@implementation MK_Barrage_FloatView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupUI];
        [self addNotification];
    }
    return self;
}

///初始化界面
-(void)setupUI{
    
}
///添加通知
-(void)addNotification{
    ///普通弹幕通知
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:NotificationOfMK_BarrageModelSend object:nil] subscribeNext:^(NSNotification*  _Nullable x) {
        
        id<MK_Barrage_Protocol> model = x.object;
        [self addBarrageAtPlayerWithString:model.barrageStr.string];
    }];
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:NotificationOfMK_UseLogInRoom object:nil] subscribeNext:^(NSNotification*  _Nullable x) {
        id<MK_Barrage_Protocol> model = x.object;
        [self addBarrageAtPlayerWithString:model.barrageStr.string];
    }];
}

#pragma mark 添加弹幕的方法
///想播放器中添加弹幕
-(void)addBarrageAtPlayerWithString:(NSString*)str{
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait ||[UIDevice currentDevice].orientation == UIDeviceOrientationPortraitUpsideDown) {
        return;
    }
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        
        CATextLayer* textLayer = [CATextLayer new];
        textLayer.string = str;
        textLayer.foregroundColor = [UIColor whiteColor].CGColor;
        textLayer.shadowColor = [UIColor blackColor].CGColor;
        textLayer.shadowOffset = CGSizeMake(4, 4);
        
        UIFont* font = [UIFont systemFontOfSize:fontsize];
        CFStringRef fontName = (__bridge CFStringRef)(font.fontName);
        CGFontRef fontRef = CGFontCreateWithFontName(fontName);
        textLayer.font = fontRef;
        
        textLayer.fontSize = fontsize;
        textLayer.contentsScale = [UIScreen mainScreen].scale;
        CGSize layerSize = [str sizeWithAttributes:@{NSFontAttributeName:font}];
        
        NSInteger arcPointY = arc4random_uniform(self.height-50);
        textLayer.frame = CGRectMake(self.width, arcPointY, layerSize.width+2, layerSize.height+2);
        [self.layer addSublayer:textLayer];
        
        CABasicAnimation* ani = [CABasicAnimation animationWithKeyPath:@"position"];
        ani.fromValue = [NSValue valueWithCGPoint:CGPointMake(textLayer.frame.origin.x, textLayer.frame.origin.y)];
        ani.toValue = [NSValue valueWithCGPoint:CGPointMake(-layerSize.width, arcPointY)];
        ani.duration = 6;
        [ani setValue:textLayer forKey:@"textLayer"];
        ani.delegate = self;
        [textLayer addAnimation:ani forKey:nil];
    }];
}

#pragma mark 动画代理
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    CATextLayer* textLayer = [anim valueForKey:@"textLayer"];
    [textLayer removeFromSuperlayer];
}

@end
